/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber, Modal,
  notification,
  Popconfirm,
  Select,
  Switch,
  Table,
  Upload
} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView, SearchForm} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import notify from "../../../components/NotificationExtra";
import _ from "lodash";
import AutoCompletePlus from "../../../common/AutoCompletePlus";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            personnel
          }) => ({...tenant, ...personnel, ...global}))
export default class ModalCreateOrEditPayroll extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    this.state = {...record};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'personnel/findPersonnelMany',
      payload: {}
    });
  }

  renderFoot = () => {
    const {foot, value, record, callback, modalRef, form} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              values.recordId = record ? record.recordId : 'RID' + new Date().valueOf();
              values.fileList = this.state.fileList;
              values.code = this.state.code;
              modalRef.close();
              callback(values);
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  picHandleCancel = () => this.setState({previewVisible: false});
  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };
  picHandleChange = ({fileList}) => {
    let isLt2M = 0;
    _.map(fileList, async file => {
      isLt2M += file.size / 1024 / 1024;
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    console.log('isLt2MisLt2M', isLt2M);
    if (isLt2M > 0.5) {
      notify({type: 'error', message: '图片文件过大或数量过多！'});
    }
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };
  callback = () => {
    this.componentDidMount();
  };
  getMaterialOpt = (list) => {
    _.map(list, item => {
      const {name = "", code = "", department = "", level = ""} = item;
      item.value = name + " " + department + " " + level + " " + code;
    });
    return list.map(opt => (
      <Option key={opt.code}
              value={opt.value}
              label={'material'}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {opt.value}
      </Option>
    ));
  };

  render() {
    const {form, model, personnelList = []} = this.props;
    const {
      previewVisible,
      previewImage,
      fileList = [],
      personnel
    } = this.state;
    const record = this.state;
    return (
      <div>
        <FormLayout form={form} cols={1}>
          <FormField
            label={'员工'}
            name={'personnel'}
            initialValue={personnel}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getMaterialOpt(personnelList)}
                          allowClear
                          onSelect={(value, option) => {
                            const {key} = option;
                            const temp = _.find(personnelList, item => {
                              return item.code === key;
                            });

                            const {name, department, inDate, level} = temp;

                            this.setState({
                              ...this.state,
                              personnel: value,
                              code: key,
                              name,
                              department,
                              inDate,
                              level
                            });

                            this.componentDidMount();
                          }}
            >
            </AutoComplete>
          </FormField>

          {this.getDicFields(model, record, this.callback)}
        </FormLayout>

        <div style={{marginLeft: '128px'}}>
          <Upload
            action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
            listType="picture-card"
            fileList={fileList}
            accept={".png,.jpg"}
            onPreview={this.picHandlePreview}
            onChange={this.picHandleChange}
            onDownload={file => {
              console.log('ondownlad', file);
            }}
            beforeUpload={(file, fileList) => {
              const isLt2M = file.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                notify({type: 'error', message: '文件过大！'});
                return isLt2M;
              }
              return false;
            }}
          >
            {this.getUploadPicButton()}
          </Upload>
          <Modal visible={previewVisible} footer={null} onCancel={this.picHandleCancel}>
            <img alt="example" style={{width: '100%'}} src={previewImage}/>
          </Modal>
        </div>

        {this.renderFoot()}
      </div>
    );
  }
}
